package com.yc.sole.framework.mybatis.page;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;

/**
 * @author yizuomin
 * @date 2022/11/23 15:09
 **/
@Data
@AllArgsConstructor
public class Paging<T extends Serializable> implements Serializable {

    @Serial
    private static final long serialVersionUID = 7154923323891963038L;

    /**
     * 数据集合
     */
    private List<T> records;
    /**
     * 总数量
     */
    private Long total;
    /**
     * 分页大小
     */
    private Long size;
    /**
     * 当前页码
     */
    private Long current;

    public Paging() {
        this.records = Collections.emptyList();
        this.total = 0L;
        this.size = 10L;
        this.current = 1L;
    }

    public Paging(long current, long size) {
        this(current, size, 0L);
    }

    public Paging(long current, long size, long total) {
        this.records = Collections.emptyList();
        this.current = Math.max(current, 1L);

        this.size = size;
        this.total = total;
    }

    public boolean hasPrevious() {
        return this.current > 1L;
    }

    public boolean hasNext() {
        return this.current < this.getPages();
    }

    public List<T> getRecords() {
        return this.records;
    }

    public Paging<T> setRecords(List<T> records) {
        this.records = records;
        return this;
    }

    public long getTotal() {
        return this.total;
    }

    public Paging<T> setTotal(long total) {
        this.total = total;
        return this;
    }

    public long getSize() {
        return this.size;
    }

    public Paging<T> setSize(long size) {
        this.size = size;
        return this;
    }

    public long getCurrent() {
        return this.current;
    }

    public Paging<T> setCurrent(long current) {
        this.current = current;
        return this;
    }

    public long getPages() {
        if (getSize() == 0) {
            return 0L;
        }
        long pages = getTotal() / getSize();
        if (getTotal() % getSize() != 0) {
            pages++;
        }
        return pages;
    }

    public long offset() {
        if (current <= 1L) {
            return 0L;
        }
        return (current - 1) * getSize();
    }
}
